<template>
	<h1 class="page-title">项目配置</h1>
	<el-form :inline="true" :model="query" @submit.native.prevent="fetch" class="search-form">
		<el-form-item>
			<el-input v-model="query.name" @change="queryChanged = true" placeholder="名称" />
		</el-form-item>
		<el-form-item>
			<el-input v-model="query.label" @change="queryChanged = true" placeholder="标识" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" :disabled="fetching" :loading="fetching" :icon="Search"
				native-type="submit">查询</el-button>
		</el-form-item>
		<el-form-item fixed="right">
			<el-button type="success" :icon="Plus" @click="create()">添加配置项</el-button>
		</el-form-item>
	</el-form>
	<div class="list-box" v-loading="fetching">
		<el-table :data="data.items" border>
			<el-table-column prop="id" label="ID" width="80" />
			<el-table-column prop="name" label="名称" width="200px" />
			<el-table-column prop="label" label="标识" width="220px" />
			<el-table-column label="配置值" min-width="200" class="cover-config">
				<template #default="scope">
					<p v-html="scope.row.value"></p>
				</template>
			</el-table-column>
			<el-table-column prop="desc" label="说明" />
			<el-table-column label="时间" width="250px">
				<template #default="scope">
					<div v-if="scope.row.created_at">
						<el-tag size="mini" type="success">创建</el-tag>
						：{{ scope.row.created_at }}
					</div>
					<div v-if="scope.row.updated_at">
						<el-tag size="mini" type="primary">更新</el-tag>
						：{{ scope.row.updated_at }}
					</div>
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作" width="120">
				<template #default="scope">
					<el-button v-if="scope.row.label !== 'hide_switch'" type="primary" size="small" :icon="Edit" circle
						@click="update(scope.row)">
					</el-button>
					<el-button v-if="scope.row.label !== 'hide_switch'" type="danger" size="small" :icon="Delete" circle
						@click="remove(scope.row)">
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<Pagination :total="data.total" :page="query.page" :sizeOptions="sizeOptions" :size="query.size"
			@pagination="fetch" />
	</div>
	<el-drawer ref="EditContainer" :title="(oldModel.id ? '编辑' : '新建') + '配置'" size="39%" v-model="showForm" direction="rtl"
		:before-close="clearForm">
		<div style="padding:10px;">
			<el-form :rules="modelRules" ref="configForm" label-position="right" label-width="80px" :model="newModel">
				<el-form-item label="类型" prop="type">
					<el-select v-model="newModel.type" :teleported="false" placeholder="选择配置值的类型" @change="typeChange">
						<el-option v-for="item in typeOptions" :key="item.value" :label="item.name" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="名称" prop="name">
					<el-input v-model="newModel.name" maxlength="20" placeholder="请输入配置名称" />
				</el-form-item>
				<el-form-item label="标识" prop="label">
					<el-input v-model="newModel.label" maxlength="30" placeholder="请输入唯一标识" />
				</el-form-item>
				<el-form-item label="配置值" prop="value">
					<el-input type="textarea" v-show="!showText" v-model="newModel.value" placeholder="请输入配置值" />
					<ImageInput v-show="showText" v-model="newModel.value" full_path business="config" key="icon"
						placeholder="上传图片或直接输入图片地址" :size="100" />
				</el-form-item>
				<el-form-item label="配置说明" prop="desc">
					<el-input type="textarea" rows="5" maxlength="200" v-model="newModel.desc" placeholder="请输入配置说明" />
				</el-form-item>
			</el-form>
			<div class="form-buttons-container">
				<el-button @click="hideForm">取 消</el-button>
				<el-button type="primary" @click="submitModel()" :icon="Check" :loading="submiting">
					{{ submiting ? '提交中 ...' : '保 存' }}
				</el-button>
			</div>
		</div>
	</el-drawer>
</template>

<script setup>

import { ref, inject } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import ImageInput from '../../components/ImageInput.vue';
import { Search, Plus, Edit, Delete, Check } from '@element-plus/icons-vue';

const http = inject('$http'),
	tools = inject('$tools'),
	router = inject('$router');

let
	configForm = ref(),
	EditContainer = ref(),
	fetching = ref(false),
	submiting = ref(false),
	queryChanged = ref(false),
	showForm = ref(false),
	showText = ref(false),
	oldModel = ref({}),
	newModel = ref({}),
	data = ref({ total: 0, items: [] }),
	query = ref({
		name: '', label: '', page: 1, size: 10
	});

let queryParams = {};

const
	sizeOptions = [10, 20, 30],
	modelTemplate = { type: 1, name: '', label: '', value: '', desc: '' },
	typeOptions = [
		{ name: "文本", value: 1 },
		{ name: "图片", value: 2 },
	],
	modelRules = {
		type: [{ required: true, message: "请选择配置类型", trigger: "blur" }],
		name: [{ required: true, message: "请输入名称", trigger: "blur" }],
		label: [{ required: true, message: "请输入标识", trigger: "blur" }],
	};

function loadQuery() {
	var queries = router.currentRoute.value.query;
	if (queries.name) query.value.name = queries.name.trim();
	if (queries.label) query.value.label = queries.label.trim();
	if (queries.page) query.value.page = parseInt(queries.page);
	if (queries.size) {
		if (sizeOptions.indexOf(queries.size) !== false) {
			query.value.size = queries.size;
		} else {
			query.value.size = sizeOptions[0];
		}
	}
	console.log(query.value);
	queryParams = tools.deepCopy(query.value);
}
loadQuery();

async function fetch(params = null) {
	if (fetching.value) return false;
	if (params && params['page']) {
		query.value = Object.assign(query.value, params);
	}
	if (queryChanged.value) {
		query.value.page = 1;
		queryChanged.value = false;
	}
	if (JSON.stringify(queryParams) !== JSON.stringify(query.value)) {
		router.push({ query: query.value })
		// 同步路由参数记录
		queryParams = tools.deepCopy(query.value);
	}
	fetching.value = true;
	const res = await http.get('/config', query.value);
	fetching.value = false;
	if (res && res.code === 200) {
		data.value.total = res.data.total;
		data.value.items = res.data.rows;
	}
}

function clearForm(done) {
	oldModel.value = {};
	configForm.value.resetFields()
	typeof done === 'function' && done();
}
function hideForm() {
	submiting.value = false;
	showForm.value = false;
}
function create() {
	newModel.value = tools.deepCopy(modelTemplate);
	showForm.value = true;
}
function update(row) {
	// 深拷贝，防止元数据被修改
	oldModel.value = JSON.parse(JSON.stringify(row));
	newModel.value = JSON.parse(JSON.stringify(row));
	showForm.value = true;
	if (row.type === 1) {
		showText.value = false;
	} else {
		showText.value = true;
	}
}
async function submitModel() {
	if (JSON.stringify(oldModel.value) === JSON.stringify(newModel.value)) {
		ElMessage({ type: 'warning', message: '内容无变动，无需保存' })
		return;
	}
	let res;
	submiting.value = true;
	if (newModel.value.id) {
		res = await http.put(`/config/${newModel.value.id}`, newModel.value);
	} else {
		res = await http.post("/config", newModel.value);
	}
	submiting.value = false;
	if (res && res.code === 200) {
		ElMessage({ type: 'success', message: res.message })
		showForm.value = false
		fetch();
	}
}
function remove(row) {
	ElMessageBox.confirm(`是否删除 "${row.name}"`, "提示", { type: "warning" }).then(async () => {
		fetching.value = true;
		let res = await http.delete(`/config/${row.id}`);
		fetching.value = false;
		if (res && res.code === 200) {
			ElMessage({ type: "success", message: res.message });
			fetch();
		}
	}).catch(e => e);
}
function typeChange() {
	if (newModel.value.type === 1) {
		showText.value = false
	} else {
		showText.value = true;
	}
}

fetch();

</script>